class Solution
{
public:
    int minimumScore(string s, string t)
    {
        map<int, int> prefixSubStrIndexTS;
        int sPos = 0;
        int tPos = 0;
        while (tPos < t.size() && sPos < s.size())
        {
            if (s[sPos] == t[tPos])
            {
                prefixSubStrIndexTS[tPos] = sPos;
                ++tPos;
            }
            ++sPos;
        }

        map<int, int> postfixSubStrIndexST;
        sPos = s.size() - 1;
        tPos = t.size() - 1;
        while (tPos >= 0 && sPos >= 0)
        {
            if (s[sPos] == t[tPos])
            {
                postfixSubStrIndexST[sPos] = tPos;
                --tPos;
            }
            --sPos;
        }

        int result = t.size();

        if (!prefixSubStrIndexTS.empty() && prefixSubStrIndexTS.rbegin()->first == t.size() - 1)
        {
            return 0;
        }

        if (!postfixSubStrIndexST.empty())
        {
            result = postfixSubStrIndexST.begin()->second;
        }

        for (auto &[tFront, sFront] : prefixSubStrIndexTS)
        {
            int tBack = t.size();
            auto sBack = postfixSubStrIndexST.upper_bound(sFront);
            if (sBack != postfixSubStrIndexST.end())
            {
                tBack = sBack->second;
            }

            result = min(result, tBack - tFront - 1);
        }

        return result;
    }
};